//
//  MemUtils.m
//  SMG2
//
//  Created by 贾  on 2017/4/1.
//  Copyright © 2017年 XiaoGang. All rights reserved.
//

#import "MemUtils.h"
#import "MKHeader.h"

@implementation MemUtils

/**
 *  MARK:--------------------插入一条记忆到记忆流--------------------
 */
+(void) insertSingleMemory:(MemDoModel*)doModel withTimeCompareType:(TimeCompareType)timeCompareType {
    if (doModel == nil) {
        return;
    }
    //1,插入行为(以后写去重)
    MemDoModel *findOld = [MemDoModel searchSingleMemoryWithWhere:[NSDictionary dictionaryWithObjectsAndKeys:@(doModel.type),@"type",
                                                                   @(doModel.fromMKId), @"fromMKId",
                                                                   @(doModel.toMKId), @"toMKId", nil]];
    if (findOld) {
        doModel.rowid = findOld.rowid;
    }else{
        [MemDoModel insertToMemory:doModel];
    }
    
    //2,记忆流
    MemFeedModel *feedModel = [[MemFeedModel alloc] init];
    feedModel.doId = doModel.rowid;
    feedModel.timeCompareType = timeCompareType;
    [MemFeedModel insertToMemory:feedModel];
}


/**
 *  MARK:--------------------查询一条普通记忆--------------------
 */
+(void) searchSingleMemory:(NSString*)fromName withDoType:(DoType)doType withToName:(NSString*)toName withSuccess:(void(^)(id response))successBlock withError:(void(^)(NSString *errorCode))errorBlock{
    //解说例子,查找关于我吃桃的记忆;
    //1,参数检查;
    if (fromName == nil || toName == nil) {
        if (errorBlock) {
            errorBlock(MEM_PARAMS_ERROR);
        }
        return;
    }
    //2,查我和桃;
    NSObject *findFromObj = [MKObject searchSingleWithWhere:[DBUtils sqlWhere_K:@"name" V:fromName] orderBy:nil withDBHelper:[DB_MK sharedInstance]];
    MKObject *findToObj = [MKObject searchSingleWithWhere:[DBUtils sqlWhere_K:@"name" V:toName] orderBy:nil withDBHelper:[DB_MK sharedInstance]];
    if (findFromObj == nil || findToObj == nil) {
        if (errorBlock) {
            errorBlock(MEM_NO_FIND);
        }
        return;
    }
    //3,查行为;
    NSDictionary *where = [NSDictionary dictionaryWithObjectsAndKeys:@(findFromObj.rowid),@"fromMKId",@(findToObj.rowid),@"toMKId",@(doType),@"type", nil];
    MemDoModel *doModel = [MemDoModel searchSingleMemoryWithWhere:where];
    //id do2 = [MemDoModel searchSingleMemoryWithWhere:[NSString stringWithFormat:@"fromMKId = %ld and toMKId = %ld and type = %ld",(long)findFromObj.rowid,(long)findToObj.rowid,(long)doType]];
    
    //4,查记忆;
    if (doModel) {
        MemFeedModel *feedModel = [MemFeedModel searchSingleMemoryWithWhere:[DBUtils sqlWhere_K:@"doId" V:@(doModel.rowid)]];
        if (feedModel) {
            if (successBlock) {
                successBlock(feedModel);
            }
            return;
        }
    }
    
    if (errorBlock) {
        errorBlock(MK_OTHER_ERROR);
    }
}


@end
